<?php
namespace app\oem\controller;
use think\Controller;
use think\Db;
use app\common\controller\OemBaseController;

class Index extends OemBaseController
{
	
    public function index()
    {
    	$id=session('d_id');
    	$data = Db::table('info_oem')->where('id',$id)->find();
    	//$data['balance'] 	 = substr($data['balance'],0,strlen($data['balance'])-2);
    	//$data['commission'] 	 = substr($data['commission'],0,strlen($data['commission'])-2);
    	$this->assign('data',$data);
    	if($data['user_level'] == 3){
    		
    		$up_id = $data['agency_id'];
    		$data1 = Db::table('info_oem')->where('id',$up_id)->find();
    		
    	}else if($data['user_level'] == 2){
    		
    		$up_id = $data['oem_id'];
    		$data1 = Db::table('info_oem')->where('id',$up_id)->find();
    		
    	}else{
    		$data1 = $data;
    	}
    	
    	$this->assign('data1',$data1);
    	return $this->fetch();
    }
	public function glj_record(){
		if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['begin_time']) && !empty($param['end_time'])){
				$where['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			}
    	}
		$where['oem_id']=session('d_id');
		$list=db('log_oem_score')->where($where)->order("add_time desc")->paginate(20);
		$this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
		return $this->fetch();
	}
	public function glj_zz(){
		$id=session('d_id');
    	$data = Db::table('info_oem')->where('id',$id)->find();
		$this->assign('level',session("user_level"));
		if($_POST){
			$mobile=input("mobile");
			$type=input("type");
			$mess="鼓励金转账给";
			if($type==1){//省代
				$db="info_oem";
				$where['user_level'] = 2;
				$mess.='服务商'.$mobile;
			}elseif($type==2){//市代 
				$db="info_oem";
				$where['user_level'] = 3;
				$mess.='服务商'.$mobile;
			}elseif($type==3){//商家 
				$db="info_agent";
				$mess.='商家'.$mobile;
			}elseif($type==4){//会员
				$db="info_user";
				$mess.='用户'.$mobile;
			}
			$where['mobile'] = input("mobile");
			$skr=db($db)->where($where)->find();
			if(!$skr){
				return json(['code'=>404,'msg'=>'收款人手机号码不存在']);
			}
			$score=input("score");
			if($score>$data['score']){
				return json(['code'=>400,'msg'=>'鼓励金不足转账失败']);
			}
			Db::startTrans();
			$res=oem_score_change(3,-$score,$mess,$data['id'],$type,$skr['id']);
			if(!$res){
				Db::rollback();
				return json(['code'=>400,'msg'=>'转账失败']);
			}
			$res=db('info_oem')->where("id",$data['id'])->setDec("score",$score);
			if(!$res){
				Db::rollback();
				return json(['code'=>400,'msg'=>'转账失败']);
			}
			if($type==1||$type==2){//省代市代
				$res=oem_score_change(6,$score,"转账收款",$skr['id'],$type);
				if(!$res){
					Db::rollback();
					return json(['code'=>400,'msg'=>'转账失败']);
				}
				$res2=db('info_oem')->where("id",$skr['id'])->setInc("score",$score);
				
			}elseif($type==3){//商家 
				$res=agent_score_change($skr['id'],10,0,0,$score,'转账收款');
				if(!$res){
					Db::rollback();
					return json(['code'=>400,'msg'=>'转账失败']);
				}
				$res2=db('info_agent')->where("id",$skr['id'])->setInc("score",$score);
			}elseif($type==4){//会员
				$res=user_score_change($skr['id'],11,$score,'转账收款');
				if(!$res){
					Db::rollback();
					return json(['code'=>400,'msg'=>'转账失败']);
				}
				$res2=db('info_user')->where("id",$skr['id'])->setInc("score",$score);
			}
			if(!$res2){
					Db::rollback();
					return json(['code'=>400,'msg'=>'转账失败']);
			}
			Db::commit();	
			return json(['code'=>400,'msg'=>'转账成功']);
		}
    	$this->assign('oem_info',$data);
    	return $this->fetch();
	}
    public function child_account()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['oem_id']=session('d_id');
			$where['user_type']=["neq",0];
			$where['user_level']=1;
		}elseif($user_level==2){//省
			$where['agency_id']=session('d_id');
			$where['user_type']=["neq",0];
			$where['user_level']=2;
		}elseif($user_level==3){//市
			$where['city_id']=session('d_id');
			$where['user_type']=["neq",0];
			$where['user_level']=3;
		}
		
    	$list=db('info_oem')->where($where)->select();
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
	public function add_account(){
		if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			$param['add_time'] 	= now_time();
			$param['user_type'] 	= input("user_type");
			$param['mobile'] 	= input("mobile");
			$param['user_name'] 	= input("user_name");
			$param['password'] 	= md5_salt(input("password"));
			$param['status'] 	= input("status");
			$param['user_level']  	= session('user_level');
			$user_level=session("user_level");
			if($user_level==1){//oem
				$param['oem_id']=session('d_id');
			}elseif($user_level==2){//省
				$param['oem_id']=session('oem_id');
				$param['agency_id']=session('d_id');
			}elseif($user_level==3){//市
				$param['oem_id']=session('oem_id');
				$param['agency_id']=session('agency_id');
				$param['city_id']=session('d_id');
			}
		
			$res = db('info_oem')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
		return $this->fetch();
	}
	public function edit_account(){
		if(request()->isPost()){
			$param['user_type'] 	= input("user_type");
			$param['mobile'] 	= input("mobile");
			$param['user_name'] 	= input("user_name");
			if(input("password")){
				$param['password'] 	= md5_salt(input("password"));
			}
			$param['status'] 	= input("status");
			$param['id']=input("id");
			$res = db('info_oem')->update($param);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
		$account=db('info_oem')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
	
	//认证资料
	public function renzheng(){
		$account=db('sys_member_verif')->alias('a')
		->join('info_oem b','a.user_id = b.id','LEFT')
		->field('a.*,b.is_verify')
		->where('a.user_id',session("d_id"))
		->where('a.user_type',2)
		->find();
		$this->assign('account',$account);
		if(request()->isPost()){
			$param['user_id'] 			= session("d_id");
			$param['id_card_front'] 	= input("id_card_front");
			$param['id_card_behind'] 	= input("id_card_behind");
			$param['bank_card_front'] 	= input("bank_card_front");
			$param['half_photo'] 		= input("half_photo");
			$param['user_type'] 		= 2;
			$param['user_name'] 		= input("user_name");
			$param['bank_name'] 		= input("bank_name");
			$param['bank_no'] 			= input("bank_no");
			$param['id_number'] 		= input("id_number");
			$param['reserve_mobile'] 	= input("reserve_mobile");
			$param['oem_id'] 			= session("d_id");
			$param['add_time'] 			= now_time();
			if($account){			
				$ress = db('sys_member_verif')->where('user_id',session("d_id"))->update($param);
			}else{
				$ress = db('sys_member_verif')->insert($param);
			}
			if($ress){
				//修改OEM的资料认证状态     0.未提交  1.已认证 2.待审核 3.驳回 
				$params['is_verify'] = 2;
				$ress = db('info_oem')->where('id',session("d_id"))->update($params);
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
		return $this->fetch();
	}
	
	
	//余额记录
	public function yue_record(){
		if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['begin_time']) && !empty($param['end_time'])){
				$where['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			}
    	}
		$where['oem_id']=session('d_id');
		$where['order_type'] = ['not in','3'];
		//余额用户类型
		$list=db('log_oem_charge')->where($where)->order('add_time desc')->paginate(20);
		$this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
		return $this->fetch();
	}
	//佣金记录
	public function yongj_record(){
		if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['begin_time']) && !empty($param['end_time'])){
				$where['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			}
    	}
		$user_level=session("user_level");
		if($user_level==1){//oem
			$where['oem_id']=session('d_id');
		}elseif($user_level==2){//省
			$where['oem_id']=session('d_id');
		}elseif($user_level==3){//市
			$where['oem_id']=session('d_id');
		}
		//佣金用户类型
		//$where['user_type'] = session("user_level");
		$list=db('log_oem_commission')->where($where)->order('add_time desc')->paginate(10);
		$this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
		return $this->fetch();
	}
	//鼓励金兑现
	public function glj_exchange(){
		$oem_info = db('info_oem')->where('id',session('d_id'))->find();
		if(request()->isPost()){
			Db::startTrans();
			$balance=input('score')/10;
			$res=oem_score_change(2,-input('score'),'鼓励金兑现扣除鼓励金',session('d_id'));
			if($res){
				$res=db('info_oem')->where("id",session('d_id'))->setDec("score",input('score'));
				if(!$res){
					Db::rollback();	
					return json(["code"=>400,'msg'=>'兑现失败1']);
				}
				$balance=$balance*0.95;//兑现扣除百分之5手续费
				$res=balance_change(4,$balance,'鼓励金兑现增加余额',session('d_id'));
				if(!$res){
					Db::rollback();	
					return json(["code"=>400,'msg'=>'兑现失败']);
				}
				$sql="update info_oem set balance=balance+$balance,income=income+$balance where id=".session('d_id');
				$res=DB::execute($sql);
				if(!$res){
					Db::rollback();	
					return json(["code"=>400,'msg'=>'兑现失败']);
				}
				$res=admin_charge($balance*0.05,3,0,0,'鼓励金兑现分佣',$oem_info['id']);
				if(!$res){
					Db::rollback();	
					return json(["code"=>400,'msg'=>'兑现失败']);
				}
				Db::commit();
				return json(["code"=>200,'msg'=>'兑现成功']);
			}else{
				Db::rollback();	
				return json(["code"=>400,'msg'=>'兑现失败']);
			}
				
		}
		$this->assign('oem_info',$oem_info);
		return $this->fetch();
		
	}
	//佣金转余额
	public function yongj_yue(){
		//获取当前用户信息
		$oem_info = db('info_oem')->where('id',session('d_id'))->find();
		if(request()->isPost()){
			// 启动事务
			Db::startTrans();			
			try{
				//查询佣金
				if(bccomp($oem_info['commission'], $_POST['commission'], 4)>=0){
					//计算佣金转为余额的金额
					$change_val = bcsub($_POST['commission'], bcmul($_POST['commission'], 0.05, 4), 4);
					
					$new_commission = bcsub($oem_info['commission'], $_POST['commission'], 4);
					$new_balance = bcadd($oem_info['balance'],$change_val, 4);
					//更新用户信息
					db('info_oem')->where('id', $oem_info['id'])->update(['balance' => $new_balance,'commission'=>$new_commission]);
					//oem佣金变化日志
					commission_change(5,$_POST['commission'],"佣金转余额扣除佣金",$oem_info['id']);
					//oem余额变化日志
					balance_change(2,$change_val,"佣金转余额增加余额",$oem_info['id']);
					// 提交事务
    				Db::commit();
					return json(['code'=>200,'msg'=>'转入成功']);
				}else{
					return json(['code'=>402,'msg'=>'转入失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
		}
		$this->assign('oem_info',$oem_info);
		
		return $this->fetch();
	}
	
	//提现
	public function yue_tixian(){
		//获取oem信息
		$oem_info = db('info_oem')->where('id',session('d_id'))->find();
		$this->assign('oem_info',$oem_info);
		
		if(request()->isPost()){
    		
			$result = true;
    		// 启动事务
			Db::startTrans();			
			try{
				//oem累计收入
				$oem_total_money = db('log_oem_charge')
											->where('oem_id',$oem_info['id'])
											->where('order_type','<>',5)
											->where('balance','>',0)
											->sum('balance');
				//检查累计收入 
//				if(bccomp($oem_total_money, $oem_info['income'], 4) != 0){
//					return json(['code'=>405,'msg'=>'提交申请失败']);
//				}
				//计算oem余额 = 累计收入 - 提现金额
				$oem_cut_money = bcsub($oem_total_money, $oem_info['total_withdrawals_money'], 4);
				//检查oem余额 
//				if(bccomp($oem_cut_money, $oem_info['balance']) != 0){
//					return json(['code'=>403,'msg'=>'提交申请失败']);
//				}
				//检查提现金额，核对余额是否合法
				if(bccomp($oem_info['balance'], $_POST['balance'], 4)>=0){
					//计算当前余额
					$cut_balance = bcsub($oem_info['balance'], $_POST['balance'], 2);
					//更新oem信息
					$rest1 = db('info_oem')->where('id', $oem_info['id'])->update(['balance'=>$cut_balance]);
					if(!$rest1)$result =false;
					
					//oem提现，余额变化日志
					$rest2 = balance_change(1,-$_POST['balance'],'余额提现',$oem_info['id']);
					if(!$rest2)$result =false;
					
					//提现日志
					$rest3 = oem_withdrawals_log($oem_info['id'],$_POST['balance'],$_POST['balance'],$rest2);
					if(!$rest3)$result =false;
					
					if($result){
						// 提交事务
	    				Db::commit();
	    				
	    				$tem_w['title']='提现申请';
						$tem=db("sms_template")->where($tem_w)->find();
						$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','');
	    				
						return json(['code'=>200,'msg'=>'提交成功']);
					}else{
						//回滚
			    		Db::rollback();
						return json(['code'=>402,'msg'=>'提交失败']);
					}
				}else{
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
    	}
		return $this->fetch();
	}
	//修改登陆密码
	public function return_password(){
		if(request()->isPost()){
			$oemid=session('d_id');
			$oem_info = Db::table('info_oem')->where('id',$oemid)->find();
			if($oem_info['password'] ==md5_salt(input('jiupwd'))){
				$result = Db::table('info_oem')->where('id', $oem_info['id'])->update(['password' => md5_salt(input("xinpwd"))]);
				if($result){
					return json(['code'=>200,'msg'=>'修改成功']);
				}else{
					return json(['code'=>402,'msg'=>'修改失败']);
				}
			}else{
				return json(['code'=>408,'msg'=>'旧密码错误']);
			}
		}
		return $this->fetch();
	}
	//修改信息
	public function show_agent()
    {
    	$data=db('info_oem')->where('id',session("d_id"))->find();
		$this->assign('data',$data);
		if(request()->isPost()){
			$param['logo'] 	= input("logo");
			$param['project_name'] 	= input("project_name");
			$param['addres'] 	= input("addres");
			$ress = db('info_oem')->where('id',session("d_id"))->update($param);
			if($ress){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
    	return $this->fetch();
    }
	
	//签约流程1
	public function qianyue_step1()
    {
    	$data=db('agent_qianyue')->where('agent_id',input("agent_id"))->find();
		$this->assign('data',$data);
		$typelist=db('sys_platform_type')->where('pid',0)->select();
		$this->assign('typelist',$typelist);
		$this->assign('agent_id',input("agent_id"));
		if(request()->isPost()){
			$param['agent_type'] 	= input("agent_type");
			$param['agent_name1'] 	= input("agent_name1");
			$param['agent_name2'] 	= input("agent_name2");
			$param['trade_type'] 	= input("trade_type");
			$param['trade_type2'] 	= input("trade_type2");
			$param['address'] 		= input("address");
			$param['service_tel'] 	= input("service_tel");
			$param['contacts'] 		= input("contacts");
			$param['job'] 			= input("job");
			$param['contact_tel'] 	= input("contact_tel");
			$param['add_time'] 		= now_time();
			$param['email'] 		= input("email");
			$param['wechat_no'] 	= input("wechat_no");
			if($data){
				$ress = db('agent_qianyue')->where('agent_id',input("agent_id"))->update($param);
			}
			if($ress){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
		if($data){
			$type2=db("sys_platform_type")->find($data['trade_type2']);
			$this->assign('type2',$type2);
		}else{
			$this->assign('type2',null);
		}
		
    	return $this->fetch();
    }
	//签约流程2
    public function qianyue_step2()
    {
    	$data=db('agent_qianyue')->where('agent_id',input("agent_id"))->find();
		$this->assign('data',$data);
		$this->assign('agent_id',input("agent_id"));
		if(request()->isPost()){
			$param['regist_name'] 		= input("regist_name");
			$param['regist_address'] 	= input("regist_address");
			$param['license'] 			= input("license");
			$param['main_business'] 	= input("main_business");
			$param['business_time1'] 	= input("business_time1");
			$param['business_time2'] 	= input("business_time2");
			$param['legal_name'] 		= input("legal_name");
			$param['document_type'] 	= input("document_type");
			$param['document_no'] 		= input("document_no");
			$param['document_time1'] 	= input("document_time1");
			$param['document_time2'] 	= input("document_time2");
			$param['add_time'] 			= now_time();
			$ress = db('agent_qianyue')->where('agent_id',input("agent_id"))->update($param);
			if($ress){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
    	return $this->fetch();
    }
	//签约流程3
    public function qianyue_step3()
    {
    	$data=db('agent_qianyue')->where('agent_id',input("agent_id"))->find();
		$this->assign('data',$data);
		$this->assign('agent_id',input("agent_id"));
		if(request()->isPost()){
			$param['account_name'] 		= input("account_name");
			$param['bank_account'] 		= input("bank_account");
			$param['open_bank'] 		= input("open_bank");
			$param['yl_mobile'] 		= input("yl_mobile");
			$param['branch_address'] 	= input("branch_address");
			$param['branch_name'] 		= input("branch_name");
			$param['add_time'] 			= now_time();
			$ress = db('agent_qianyue')->where('agent_id',input("agent_id"))->update($param);
			if($ress){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
    	return $this->fetch();
    }
	//签约流程4
    public function qianyue_step4()
    {
    	$data=db('agent_qianyue')->where('agent_id',input("agent_id"))->find();
		$this->assign('data',$data);
		$this->assign('agent_id',input("agent_id"));
		if(request()->isPost()){
			$param['my_pic'] 		= input("my_pic");
			$param['ids_pic1'] 		= input("ids_pic1");
			$param['ids_pic2'] 		= input("ids_pic2");
			$param['license_pic'] 	= input("license_pic");
			$param['bank_pic'] 		= input("bank_pic");
			$param['door_pic'] 		= input("door_pic");
			$param['indoor_pic'] 	= input("indoor_pic");
			$param['accredit_pic'] 	= input("accredit_pic");
			$param['other_pic'] 	= input("other_pic");
			$param['add_time'] 		= now_time();
			$ress = db('agent_qianyue')->where('agent_id',input("agent_id"))->update($param);
			if($ress){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
    	return $this->fetch();
    }
	
	//签约流程5
    public function qianyue_step5()
    {
    	$data=Db::table('agent_qianyue')
    	->alias('a')
    	->join('sys_platform_type w','a.trade_type = w.id')
		->join('sys_platform_type b','a.trade_type = b.pid and a.trade_type2 = b.id')
    	->field('a.*,w.type_name type_name,b.type_name type_name2')
    	->where('a.agent_id',input("agent_id"))
    	->find();
		$info=db('info_agent')->where('id',input("agent_id"))->find();
		$this->assign('data',$data);
		$this->assign('agent_id',input("agent_id"));
		$this->assign('is_state',$info['is_state']);
    	return $this->fetch();
    }
	
	//签约流程
    public function qianyue_step()
    {
    	$data=Db::table('agent_qianyue')
    	->alias('a')
    	->join('sys_platform_type w','a.trade_type = w.id','left')
		->join('sys_platform_type b','a.trade_type = b.pid and a.trade_type2 = b.id','left')
    	->field('a.*,w.type_name type_name,b.type_name type_name2')
    	->where('a.agent_id',input("agent_id"))
    	->find();
		$info=db('info_agent')->where('id',input("agent_id"))->find();
		$this->assign('data',$data);
		$this->assign('agent_id',input("agent_id"));
		$this->assign('is_state',$info['is_state']);
    	return $this->fetch();
    }

	//签约信息保存
    public function qianyue_save()
    {
		$this->assign('agent_id',input("agent_id"));
		if(request()->isPost()){
			$param['state'] = 2;
			$param['add_time'] 	= now_time();
			$ress = db('agent_qianyue')->where('agent_id',input("agent_id"))->update($param);
			$where['is_state'] = 2;
			$where['add_time'] 	= now_time();
			$ress = db('info_agent')->where('id',input("agent_id"))->update($where);
			if($ress){
				return json(['code'=>200,'msg'=>'提交成功']);
			}else{
				return json(['code'=>402,'msg'=>'提交失败']);
			}
		}
    	return $this->fetch();
    }
    
    //鼓励金充值
     public function yue_score()
    {
    	$data=db('info_oem')->where('id',session("d_id"))->find();
    	
    	$code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/recharge?user_id=".$data['id'].'&user_type=1&change_type=1&';
    	
    	$data['code_url'] = $code_url;
    	$this->assign('data',$data);
    	$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
	
	public function get_trades(){
		$data=db('sys_platform_type')->where('pid',input("trade_id"))->select();
		return json(["data"=>$data]);
	}
    
}
